Skip to content

Combat 4.1: Move damage formulas into combat.yml - #387

Merged
Travja merged 6 commits into
devfrom
combat-4.1-formulas-in-combat-yml
Nov 18, 2026
Merged

Travja merged 6 commits into
devfrom
combat-4.1-formulas-in-combat-yml

Conversation

@Travja

@Travja Travja commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Closes #371. Part of #365.

The numeric formulas of DamageCalculator become four named expressions in a new combat.yml, compiled once at load with Codex's Evaluator.compile and evaluated per damage type of every hit. With the shipped default file the numbers are identical to today's, bit for bit. With the legacy preset they are identical to today's legacy-combat: true.

dev has been merged into this branch (4.2 and 4.2b landed meanwhile). The conflicts were in EngineCfg (both sides added a field) and in the notes doc (both sides added a section and a status row); nothing else needed resolving, and the whole suite passes on the merged result.

Stage inventory

What I read: DamageCalculator and DamageManager.onDamageRPGStart / handleDamageModifiers. Only formulas became expressions; rolls, events and ordering stay in Java.

# Stage (in order) Numbers it computes Kind In this PR
1 Dodge (handleDamageModifiers) Rnd < dodge_rate && Rnd >= accuracy_rate; Dodge event; cancel Control flow (roll) Unchanged
2 Critical Rnd < crit_rate; modifier = CRITICAL_DAMAGE or 1 if that is 0 Control flow (roll), then a lookup Unchanged
3 PvP or PvE choice which defense and damage stat to read Branch (both sides players) Unchanged
4 Stat to modifier conversions pvpDamage = 1 + stat/100, pvpDefense = 1 + stat/100, penetration = 1 - stat/100, direct = 0/100 (direct damage is switched off) Fixed formulas, one per stat Left in Java (see below)
5 Block rate and damage get the shield bonus config (block-rate-bonus, block-damage-bonus); roll; modifier 1 - blockDamage/100; shield durability roll 100/(level+1) Config-dependent, roll Unchanged
6 Pre event, MythicMobs faction lookup Event, lookup Unchanged
7 Attack power custom-cooldown metadata or the stat's modifier; 1 for skill damage Lookup, branch Unchanged
8 Enchant protection getEnchantModifier Lookup (not read for formulas, not touched) Unchanged
9 Scaling (calculator) damage * pvp_pve_damage * crit * entity_type * faction * enchant * attack_power * block, attack power skipped for exempt events Fixed formula damage-scaling
10 Direct part (calculator) direct = scaled * direct_fraction; then max(0, scaled - direct) Fixed formula plus bookkeeping direct-damage (the subtraction stays in Java)
11 Defense value (calculator) max(0, defense * pvp_pve_defense * penetration) Fixed formula defense-value
12 Mitigation (calculator) default: max(0, d * (1 - max(def/5, def - 4d/max(1, toughness+8)) * protection * 0.05)); legacy-combat: max(0, d * (1 - def * protection * 0.01)) Branches on legacy-combat defense-mitigation, one text per preset
13 Total and cancel total + invulnerableProt < 0.001 cancels Constant threshold, control flow Unchanged
14 Post effects, Exit Events Unchanged

Stage 4 is arithmetic too, but each line converts one stat into a modifier and lives in the stats-reading code, which 4.2 (stat caching) rewrote in parallel. I left it alone to keep this PR inside "formula evaluation and config loading". It is the obvious next candidate if you want more of it configurable.

combat.yml layout and the full default file

Top level keys: preset (default or legacy) and expressions (optional overrides, keyed by expression name). The shipped file lists each default expression commented out beside its documentation, so that the legacy preset's difference stays visible.

src/main/resources/combat.yml
# Divinity combat formulas.
#
# Every number the damage calculator computes with a formula is an expression in this file. Expressions are
# compiled when the plugin loads and evaluated once per damage type of every hit. Rolls (dodge, block, critical
# chance), event firing and ordering are not formulas and cannot be changed here.
#
# Changing nothing keeps the combat Divinity has always had. This file replaces 'combat.legacy-combat' in
# engine.yml: servers that had it set to true were moved to 'preset: legacy' automatically, and the old key is now
# ignored.
#
# A formula that does not compile, uses a variable that is not listed for it, or gives NaN or infinity when tested
# at load is reported once in the console and that one expression falls back to the chosen preset's own. If a
# formula gives NaN or infinity in the middle of a fight (for example a division by zero on an unusual hit), the
# preset's expression is used for that hit instead. Combat never stops because of a formula in this file.
#
# Syntax: numbers, variables, + - * / % ^, unary minus, brackets, and the functions min, max, abs, sqrt, sum, avg,
# floor, ceil, round, sin, cos, tan, ln, log, plus the constants pi and e. Notes: '^' is left associative
# (2^3^2 is (2^3)^2). A '^' followed by a minus is rejected: write '2^(-1)', not '2^-1', because Codex's parser can
# compute the second form wrongly without complaint. Variable names are written exactly as listed below (lowercase,
# with underscores).

# Which set of default expressions to start from.
#   default - the combat of current versions.
#   legacy  - as 'default', but with the old defense formula (what 'legacy-combat: true' used to give).
preset: default

# Override single expressions here. Only the keys you list are changed, everything else follows the preset.
# Each commented line below is the expression the 'default' preset uses. Remove the '#' and edit it to override.
# Where the 'legacy' preset differs, its expression is shown too.
#
# The expressions of one damage type are evaluated in this order for every hit:
#   damage-scaling -> direct-damage -> (when a defense applies) defense-value -> defense-mitigation
expressions:
  # damage-scaling: the damage of one damage type after every multiplier.
  #   damage             the damage of this type before any modifier
  #   pvp_pve_damage     1 + the attacker's PvE or PvP damage stat / 100 (PvP when both sides are players)
  #   critical           1, or the attacker's critical damage when the critical roll succeeded
  #   entity_type        the damage type's modifier for the victim's entity type (1 if none)
  #   faction            the damage type's modifier for the victim's MythicMobs faction (1 if none)
  #   enchant_protection the victim's enchantment protection factor against this cause of damage
  #   attack_power       the attacker's attack cooldown modifier (always 1 for hits that are exempt from it)
  #   block              1, or 1 - the victim's block damage stat / 100 when the block roll succeeded
  # damage-scaling: "damage * pvp_pve_damage * critical * entity_type * faction * enchant_protection * attack_power * block"

  # direct-damage: the part of the scaled damage that skips the defense. The calculator itself takes it out of the
  # damage (never below 0) and adds it back after the defense; that bookkeeping is not configurable.
  #   damage             the result of damage-scaling
  #   direct             the fraction of the damage that is direct (0 today: direct damage is switched off)
  # direct-damage: "damage * direct"

  # defense-value: the victim's defense value for the damage type, before it is used by defense-mitigation.
  # Only evaluated when the damage type has a defense and there is damage left after the direct part.
  #   defense            the victim's value of the defense attached to this damage type
  #   pvp_pve_defense    1 + the victim's PvE or PvP defense stat / 100 (PvP when both sides are players)
  #   penetration        1 - the attacker's penetration stat / 100
  # defense-value: "max(0, defense * pvp_pve_defense * penetration)"

  # defense-mitigation: the damage left after the defense. The calculator reports damage minus this as 'defended'.
  #   damage             the damage after the direct part was taken out
  #   defense            the result of defense-value
  #   protection         the defense's protection factor
  #   toughness          the victim's armor toughness (used by the default formula only)
  # defense-mitigation: "max(0, damage * (1 - max(defense / 5, defense - 4 * damage / max(1, toughness + 8)) * protection * 0.05))"
  # legacy preset:
  # defense-mitigation: "max(0, damage * (1 - (defense * protection * 0.01)))"

Variables

Variables are bound by position in the order below (CombatExpression is the single source; a test checks it against the shipped file). Names use underscores because a hyphen is the minus operator. pvp_pve_damage and pvp_pve_defense are the PvP values when both sides are players, hence the names.

Expression Variables, in order
damage-scaling damage, pvp_pve_damage, critical, entity_type, faction, enchant_protection, attack_power, block
direct-damage damage, direct
defense-value defense, pvp_pve_defense, penetration
defense-mitigation damage, defense, protection, toughness

Migration

  • If combat.yml does not exist, it is written from the shipped file with preset: set from the old combat.legacy-combat key of engine.yml (true gives legacy; false or absent gives default). When the old key was present, one line is logged: Moved 'combat.legacy-combat: X' from engine.yml to combat.yml (preset: P). The old key is now ignored.
  • An existing combat.yml is never overwritten (the write uses create-new, so even a file that appears between the check and the write survives). Migration is idempotent: later loads change nothing and log nothing.
  • Once the file exists the old key is ignored, even if it is still in engine.yml. The shipped engine.yml no longer has the key; existing servers' files are left alone.
  • If the file cannot be written, the old key still picks the preset for that run and one warning is logged. A file that cannot be parsed is left as it is, the default preset is used and one warning is logged.

Reload

CombatCfg.load runs from Divinity.setConfig(), right after EngineCfg. The plugin's real reload (Divinity#reload, which goes through ConfigManager.setup to setConfig) therefore re-reads combat.yml, and a migration on reload sees the old key EngineCfg has just read. This is exercised by CombatReloadTest, which calls the real plugin.reload() under MockBukkit: edits to the preset and to expressions are picked up; an old engine.yml key with no combat.yml migrates to the matching preset; an existing combat.yml is kept and the old key ignored. I did not look for a command that triggers that reload from a player or console; I found only the per-module reload commands.

Failure behaviour

  • At load, per expression: a syntax error, an unknown variable or function, a non-text value, an empty text, a ^ followed by a minus (see below), or a result that is NaN or infinite for ordinary sample values is reported once, naming the key and the reason, and that one expression uses the chosen preset's text (the legacy preset falls back to legacy, not to default). The others are unaffected. An unknown preset name or an unknown expression key is reported once and ignored.
  • At hit time: an overridden expression that gives NaN or infinity (or throws) is replaced by the preset's result for that hit, with one warning per expression per load. The calculator never throws because of a config formula. A preset's own expression is not second-guessed, so a hit that produced NaN or infinity before still does, as it always did.
  • Negative exponents: Javaluator, the parser bundled in Codex, computes x * 2^-1 wrongly without complaining (defense * 2^-1 gives -900 for defense = 30; the right answer is 15). The old string evaluator gives the same wrong number, so it is not new in Evaluator.compile. Until it is fixed in Codex, any override in which ^ is followed (ignoring whitespace) by a minus is rejected at load, with a message telling the admin to bracket the exponent (2^(-1)), and falls back like any other invalid formula. Follow-up for the Codex repo: fix the unary-minus-after-^ parse in Javaluator; the check in CombatFormulas (NEGATIVE_EXPONENT) can then be removed.

Thread safety

DamageCalculator holds no state between calls: every evaluation builds its own argument array, so one calculator can be shared between threads and kept across hits. Today DamageManager still builds one per hit on the main thread (4.2 did not change that), so this is a guard against a future change rather than a fix for a current bug. CombatFormulas is immutable apart from one warn-once flag per expression, and Codex's CompiledExpression is thread-safe. An earlier revision of this PR reused argument arrays inside the calculator to avoid the allocation; that saved nothing measurable (see below) and made sharing a calculator unsafe, so it was removed.

Benchmark

DamageCalculatorBenchmark (test sources, a main, not a test) sends the same pre-generated inputs through ReferenceDamageCalculator (the replaced Java formulas, verbatim) and through the configured calculator. A hit is one calculator and three damage types, two of them defended. Both give identical bits before timing starts. Median of 7 rounds per run, several runs on one machine:

hits/s
Before (Java formulas) 23M to 40M
After (combat.yml, Evaluator.compile, array per call) 1.9M to 2.3M
Ratio 10x to 17x slower (typically about 15x)

That is roughly 450 ns against 30 ns per hit, which is ten evaluations at about 35 to 45 ns each. The configured formulas are faster than Javaluator's string evaluation (about 35 ns against about 3,400 ns per evaluation, as measured in Codex), which is what the compile step is for, but they are not faster than inlined Java. This is over the 1.5x this PR first aimed for, and it is accepted: 400 to 450 ns per hit is small against a full hit through DamageManager, which is far more expensive (event firing, stat reads); I did not measure a full hit. The figures are calculator-only and the Java baseline is tiny because the JIT inlines it. For reference, a first version of this branch built on Codex's string evaluation, before it had a compile step, was about 1,700x slower.

Allocating an argument array per evaluation instead of reusing one per calculator made no measurable difference: with reused arrays the configured side ran at 1.8M to 2.1M hits/s in the same session, with an array per call at 1.9M to 2.3M, which is inside the run-to-run noise. (The benchmark was not re-run after merging dev; the calculator is unchanged by the merge.)

What is deliberately not included

  • Stat caching (4.2), events (4.3), the Thorns fix (4.2b) and any clean-up.
  • The stat to modifier conversions (stage 4), the block and shield settings, the enchant modifier and the post effects. They stay in Java and in engine.yml.
  • Any change to how stats are read from entities and items.
  • Any change to Codex.
  • A command to switch presets at runtime.
  • Removing the deprecated EngineCfg.LEGACY_COMBAT / Modifiers.legacyCombat switch. It stays so the untouched legacy tests keep selecting the legacy preset (CombatCharacterizationTest, DamageCalculatorTest, and 4.2's EntityStatSnapshotTest all rely on it); nothing in production sets it, and the old engine.yml key is read only by migration, so a stale legacy-combat: true cannot override combat.yml. Removal is Phase 5.

Tests

  • Characterization tests touched: none. CombatCharacterizationTest and DamageCalculatorTest are unmodified and pass.
  • One existing test changed outside that set: DependencyRequirementTest.minimumCodexVersion_... follows MIN_CORE_VERSION to 1.3.0-dev.2 (the first Codex build with Evaluator.compile); 1.3.0-dev.1 is now asserted to be too old.
  • New: CombatFormulasTest (25), CombatCfgTest (18) and CombatReloadTest (4).
    • Both presets equal the Java formulas bit for bit over 40,000 random hits (ReferenceDamageCalculator is a verbatim copy of the old arithmetic), and one reused calculator equals it over 10,000 varied calls.
    • One calculator shared between eight threads, 20,000 calls each, gives every call the same result as the reference, for both presets.
    • Each of the four expressions overridden changes the result as expected; numbers are accepted as expressions; overrides apply to the legacy preset too.
    • Broken formulas (syntax error, unknown variable, unknown function, 2^-1, defense * 2^-1, defense * 2 ^ -1 and other spellings, division by zero, 0/0, empty, wrong type) fall back with one message naming the key, to the chosen preset's text; a formula that only breaks during a hit falls back for that hit and warns once. 2^(-1) and defense - 2^2 are accepted.
    • Migration with the old key true, false and absent; an existing file is never overwritten; idempotency; the old key ignored once the file exists; an unwritable folder; reload picks up preset and expression changes; an unparseable file, unknown preset and unknown key; the shipped file against the code.
    • The real plugin reload (see "Reload").
  • Whole suite on the merged result, run as the notes describe with output to a file: mvn test exit code 0, 289 run, 0 failures, 0 errors, 2 skipped (the two trident tests in VanillaWrapperListenerTest).

Break-it checks (each reverted afterwards, files compared byte for byte)

Break Tests that failed
Swap the default and legacy defense-mitigation texts 33 (existing CombatCharacterizationTest and DamageCalculatorTest among them)
Drop a variable binding (protection not passed) 37
Fallback uses the default preset's text for every preset 12
Calculator keeps its scaling arguments in a shared field again 1 (the shared-between-threads test), in 3 runs out of 3
Migration overwrites an existing combat.yml 9
Migration ignores the old key 4
Negative-exponent check removed 1 (the rejection test, which covers five spellings)
CombatCfg.load moved before EngineCfg in setConfig 1 (reload_readsTheOldKeyFromEngineYmlBeforeMigrating)
CombatCfg.load removed from setConfig 3 (two failures and an error in CombatReloadTest)

The break-it checks were run before dev was merged in; the counts include only this PR's tests and the two existing calculator test classes. Two earlier rows about reused argument arrays were removed with that design.

Open questions

None open from the review. Follow-up outside this PR: the Codex parser fix above, and Phase 5 removal of the deprecated legacy switch.


Generated by Claude Code

The four formulas of DamageCalculator become named expressions in a new
combat.yml with a default and a legacy preset, per-expression overrides,
automatic migration of the old legacy-combat key, and a per-expression
fallback to the preset when a formula is broken.

Expressions are compiled through Formulas, which wraps Codex's string
evaluation for now. It is temporary: Codex has no compile step yet, and
it is about 1700x slower than the Java formulas on the calculator
benchmark. It is to be replaced by Evaluator.compile once published.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FaEyTrDtJEM6YN1zxnDP6d
Replaces the temporary string-evaluating Formulas with Codex's
CompiledExpression, reuses one argument array per expression in the
calculator, and raises MIN_CORE_VERSION to 1.3.0-dev.2.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FaEyTrDtJEM6YN1zxnDP6d
@Travja Travja added the build:major label Nov 16, 2026 — with Claude
… real reload

- A '^' followed by a minus is rejected at load: Codex's parser can compute
  it wrongly without complaint.
- pve_damage and pve_defense become pvp_pve_damage and pvp_pve_defense,
  since they are the PvP values when both sides are players.
- CombatReloadTest goes through the plugin's real reload.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FaEyTrDtJEM6YN1zxnDP6d
@Travja
Travja marked this pull request as ready for review November 18, 2026 02:41
DamageCalculator reused argument arrays to save an allocation per
evaluation. Measured on the benchmark that saved nothing noticeable, and
it made sharing a calculator between threads unsafe, which the stat
snapshots (4.2) may want. Each evaluation now builds its own array.

Adds a test that shares one calculator between eight threads.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FaEyTrDtJEM6YN1zxnDP6d
Resolves conflicts with 4.2 (stat snapshots) and 4.2b in EngineCfg (both
sides added a field) and in the notes doc (both sides added a section and
a status row).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FaEyTrDtJEM6YN1zxnDP6d
@Travja
Travja merged commit 23f58cc into dev Nov 18, 2026
2 checks passed
@Travja
Travja deleted the combat-4.1-formulas-in-combat-yml branch November 18, 2026 05:13
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Combat 4.1: Move damage formulas into combat.yml

2 participants